<template>
  <van-nav-bar title="地址列表" left-text="" left-arrow @click-left="goBack" />

  <!-- 订单选中地址 -->
  <van-address-list
    v-if="action=='order'"
    v-model="chosenAddressId"
    :list="addresslist"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    @select="selectedOrder"
  />

  <!-- 地址表 -->
  <van-address-list
    v-else
    v-model="chosenAddressId"
    :list="addresslist"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    @select="selected"
  />
</template>

<script setup>
import { onBeforeMount } from "vue"

const goBack = () => { proxy.$router.go(-1) }
const { proxy } = getCurrentInstance()
const LoginUser = reactive(proxy.$cookies.get("LoginUser"))

const chosenAddressId = ref()
const addresslist = ref([])
const action = ref(proxy.$route.query.action ?? '');

// 挂载前加载出数据
onBeforeMount(() => {
  getAddressData()
})
const getAddressData = async () => {
  let result = await Api.AddressIndex({ busid: LoginUser.id })
  if (result.code == 1) {
    console.log(result.data);
    result.data.forEach(item => {
      // cartids
      addresslist.value.push({
        id: item.id,
        name: item.consignee,
        tel: item.mobile,
        // 省市区+详细地址
        address: item.region_text + item.address,
        // 是否为默认地址
        sDefault: item.status == '1' ? true : false
      })

      // 设置默认选中
      if (item.status == '1') {
        chosenAddressId.value = item.id
      }
    });
  }
}

// 添加地址
const onAdd = async () => {
  proxy.$router.push('/business/address/add')
}

// 编辑地址
const onEdit = async (item) => {
  proxy.$router.push({
    path: '/business/address/edit',
    query: {
      addressid: item.id
    }
  })
}

// 选中设为默认地址
const selected = async (val) => {
  let result = await Api.AddressCheck({ busid: LoginUser.id, addressid: val.id })
  if (result.code == 1) {
    showSuccessToast({
      message: result.msg
    });
    setInterval(() => {
      window.location.reload()
    }, 1000);
  } else {
    showFailToast(result.msg);
  }
}

// 订单切换地址
const selectedOrder = (val) => {
  console.log(val);
  proxy.$cookies.set("address", {
    id: val.id,
    name: val.name,
    tel: val.tel
  })
  goBack()
}
</script>